package com.qiguliuxing.dts.merchant.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.merchant.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.merchant.support.MerchantResponseUtils;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsGoods;
import com.qiguliuxing.dts.db.domain.DtsGroupon;
import com.qiguliuxing.dts.db.domain.DtsGrouponRules;
import com.qiguliuxing.dts.merchant.support.AuthSupport;
import com.qiguliuxing.dts.service.base.DtsGoodsService;
import com.qiguliuxing.dts.service.base.DtsGrouponRulesService;
import com.qiguliuxing.dts.service.base.DtsGrouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qiguliuxing.dts.merchant.support.MerchantResponseCode.DISCOUNT_BEYOND_PRICE;

/**
 * 商户团购管理接口
 * @author qiguliuxing
 * @since 1.0.0
 */
@RestController
@RequestMapping("/merchant/groupon")
@Validated
@Api(tags = ApiAdminConsts.Groupon.PARENT)
public class MerchantGrouponController {
	private static final Logger logger = LoggerFactory.getLogger(MerchantGrouponController.class);

	@Autowired
	private DtsGrouponRulesService rulesService;
	@Autowired
	private DtsGoodsService goodsService;
	@Autowired
	private DtsGrouponService grouponService;

	@GetMapping("/listRecord")
	@RequiresPermissions("merchant:groupon:read")
	@RequiresPermissionsDesc(menu = { "推广管理", "团购管理" }, button = "详情")
	@ApiOperation(value = ApiAdminConsts.Groupon.READ)
	@WebLog(description = ApiAdminConsts.Groupon.READ,excludes = {LogParamsConsts.RESPONSE})
	public Object listRecord(
			@ApiParam(value = "规则id") String rulesId,
			@ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
			@ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
			@ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
			@ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		//需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
		List<Integer> brandIds = new ArrayList<Integer>();
		brandIds.add(AuthSupport.merchantBrandId());
		List<DtsGroupon> grouponList = null;
		long total = 0L;
		if (brandIds == null || brandIds.size() == 0) {
			grouponList = grouponService.querySelective(rulesId, page, limit, sort, order);
			total = PageInfo.of(grouponList).getTotal();
		} else {
			grouponList = grouponService.queryBrandGroupons(brandIds,rulesId, page, limit, sort, order);
			total = PageInfo.of(grouponList).getTotal();
		}

		List<Map<String, Object>> records = new ArrayList<>();
		for (DtsGroupon groupon : grouponList) {
			try {
				Map<String, Object> recordData = new HashMap<>();
				List<DtsGroupon> subGrouponList = grouponService.queryJoinRecord(groupon.getId());
				DtsGrouponRules rules = rulesService.queryById(groupon.getRulesId());
				DtsGoods goods = goodsService.findById(rules.getGoodsId().intValue());

				recordData.put("groupon", groupon);
				recordData.put("subGroupons", subGrouponList);
				recordData.put("rules", rules);
				recordData.put("goods", goods);

				records.add(recordData);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", records);
		return ResponseUtils.ok(data);
	}

	@GetMapping("/list")
	@RequiresPermissions("merchant:groupon:list")
	@RequiresPermissionsDesc(menu = { "推广管理", "团购管理" }, button = "查询")
	@ApiOperation(value = ApiAdminConsts.Groupon.LIST)
	@WebLog(description = ApiAdminConsts.Groupon.LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "商品id") String goodsId,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		//需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
		List<Integer> brandIds = new ArrayList<Integer>();
		brandIds.add(AuthSupport.merchantBrandId());
		
		List<DtsGrouponRules> rulesList = null;
		long total = 0L;
		if (brandIds == null || brandIds.size() == 0) {
			rulesList = rulesService.querySelective(goodsId, page, limit, sort, order);
			total = PageInfo.of(rulesList).getTotal();
		} else {
			rulesList = rulesService.queryBrandGrouponRules(brandIds,goodsId, page, limit, sort, order);
			total = PageInfo.of(rulesList).getTotal();
		}
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", rulesList);
		return ResponseUtils.ok(data);
	}

	private Object validate(DtsGrouponRules grouponRules) {
		Long goodsId = grouponRules.getGoodsId();
		if (goodsId == null) {
			return ResponseUtils.badArgument();
		}
		BigDecimal discount = grouponRules.getDiscount();
		if (discount == null) {
			return ResponseUtils.badArgument();
		}
		Integer discountMember = grouponRules.getDiscountMember();
		if (discountMember == null) {
			return ResponseUtils.badArgument();
		}
		LocalDateTime expireTime = grouponRules.getExpireTime();
		if (expireTime == null) {
			return ResponseUtils.badArgument();
		}

		return null;
	}

	@PostMapping("/update")
	@RequiresPermissions("merchant:groupon:update")
	@RequiresPermissionsDesc(menu = { "推广管理", "团购管理" }, button = "编辑")
	@ApiOperation(value = ApiAdminConsts.Groupon.UPDATE)
	@WebLog(description = ApiAdminConsts.Groupon.UPDATE,persistence = true)
	public Object update(@RequestBody DtsGrouponRules grouponRules) {
		Object error = validate(grouponRules);
		if (error != null) {
			return error;
		}

		Integer goodsId = grouponRules.getGoodsId().intValue();
		DtsGoods goods = goodsService.findById(goodsId);
		if (goods == null) {
			return ResponseUtils.badArgumentValue();
		}

		//如果设置的折扣价格为0或者负数
		if (grouponRules.getDiscount().compareTo(new BigDecimal(0)) <= 0) {
			return ResponseUtils.badArgumentValue();
		}

		//验证设置的折扣是否大于商品金额
		if (grouponRules.getDiscount().compareTo(goods.getRetailPrice()) > 0) {
			logger.error("推广管理->团购管理->编辑错误:{}", DISCOUNT_BEYOND_PRICE.desc());
			return MerchantResponseUtils.fail(DISCOUNT_BEYOND_PRICE);
		}

		logger.info("折扣金额：{},是否大于0 ：{}，是否大于商品金额：{}",grouponRules.getDiscount(),
				(grouponRules.getDiscount().compareTo(new BigDecimal(0)) <= 0),
				(grouponRules.getDiscount().compareTo(goods.getRetailPrice()) > 0));

		grouponRules.setGoodsName(goods.getName());
		grouponRules.setPicUrl(goods.getPicUrl());

		if (rulesService.updateById(grouponRules) == 0) {
			logger.info("推广管理->团购管理->编辑 失败：{}", "更新数据出错！");
			return ResponseUtils.updatedDataFailed();
		}
		return ResponseUtils.ok();
	}

	@PostMapping("/create")
	@RequiresPermissions("merchant:groupon:create")
	@RequiresPermissionsDesc(menu = { "推广管理", "团购管理" }, button = "添加")
	@ApiOperation(value = ApiAdminConsts.Groupon.CREATE)
	@WebLog(description = ApiAdminConsts.Groupon.CREATE,persistence = true)
	public Object create(@RequestBody DtsGrouponRules grouponRules) {
		Object error = validate(grouponRules);
		if (error != null) {
			return error;
		}
		Long goodsId = grouponRules.getGoodsId();
		DtsGoods goods = null;
		/**
		 * 如果输入的值为INT范围内，则先用goodsId找,如果超出范围，
		 * 如果未找到，则转换为goodsSn找再找商品
		 */
		if (goodsId.intValue() < Integer.MAX_VALUE) {
			goods = goodsService.findById(goodsId.intValue());
		}
		if (goods == null) {
			goods = goodsService.findByGoodsSn(goodsId.toString());
		}
		
		if (goods == null) {
			return ResponseUtils.badArgumentValue();
		}

		//如果设置的折扣价格为0或者负数
		if (grouponRules.getDiscount().compareTo(new BigDecimal(0)) <= 0) {
			return ResponseUtils.badArgumentValue();
		}

		//验证设置的折扣是否大于商品金额
		if (grouponRules.getDiscount().compareTo(goods.getRetailPrice()) > 0 ) {
			logger.error("推广管理->团购管理->添加错误:{}", DISCOUNT_BEYOND_PRICE.desc());
			return MerchantResponseUtils.fail(DISCOUNT_BEYOND_PRICE);
		}

		logger.info("折扣金额：{},是否大于0 ：{}，是否大于商品金额：{}",grouponRules.getDiscount(),
				(grouponRules.getDiscount().compareTo(new BigDecimal(0)) <= 0),
				(grouponRules.getDiscount().compareTo(goods.getRetailPrice()) > 0));

		grouponRules.setGoodsId(goods.getId().longValue());//最终存库只存商品id
		grouponRules.setGoodsName(goods.getName());
		grouponRules.setPicUrl(goods.getPicUrl());

		rulesService.createRules(grouponRules);
		return ResponseUtils.ok(grouponRules);
	}

	@PostMapping("/delete")
	@RequiresPermissions("merchant:groupon:delete")
	@RequiresPermissionsDesc(menu = { "推广管理", "团购管理" }, button = "删除")
	@ApiOperation(value = ApiAdminConsts.Groupon.DELETE)
	@WebLog(description = ApiAdminConsts.Groupon.DELETE,persistence = true)
	public Object delete(@RequestBody DtsGrouponRules grouponRules) {
		Integer id = grouponRules.getId();
		if (id == null) {
			return ResponseUtils.badArgument();
		}
		rulesService.delete(id);
		return ResponseUtils.ok();
	}
}
